package org.yuezejian.alarm.config;

import org.yuezejian.alarm.netty.MultiNettyClientManager;
import org.yuezejian.alarm.netty.enums.ClientType;
import org.yuezejian.alarm.netty.handler.ClientTCPHandler;
import org.yuezejian.alarm.properties.TcpProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

import static java.lang.Thread.sleep;

/**
 * TCP 客户端启动
 *
 * @author yuezejian
 * @since 2024.8.1
 */
@Slf4j
@Component
public class TCPClientStarterConfig implements SmartInitializingSingleton {

    @Autowired
    private TcpProperties tcpProperties;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private MultiNettyClientManager multiNettyClientManager;

    @Override
    public void afterSingletonsInstantiated() {
        try {
            log.info("开始连接TCP服务端");
            for (TcpProperties.PortConfig portConfig : tcpProperties.getClient()) {
                threadPoolExecutor.execute(() -> {
                    try {
                        String client = portConfig.getIp()+":"+ portConfig.getPort();
                        multiNettyClientManager.addClient(client, portConfig.getIp(), portConfig.getPort(), ClientTCPHandler.class.getSimpleName(), ClientType.TCP);
                        log.info("Client added successfully: " + client);
                    } catch (IllegalArgumentException e) {
                        log.error("Error adding client: " + e.getMessage());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 处理线程中断
                       log.error("Error starting client: " + e.getMessage());
                    }
                    try {
                        sleep(10000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("TCP client 异常", e);
            throw e;
        }
    }

}
